<template>
	<div ref="chart" style="width: 100%; height: 600px;"></div>
</template>

<script>
	import * as echarts from 'echarts';

	export default {
		data() {
			return {
				chart: null,
				nodes: [{
						name: 'Root',
						level: 0,
						expanded: true,
						children: [{
								name: 'Node1',
								level: 1,
								expanded: false,
								children: []
							},
							{
								name: 'Node2',
								level: 1,
								expanded: false,
								children: []
							},
						],
					},
					// 注意：这里不直接包含子节点的详细信息，而是在点击事件中动态处理  
				],
				nodeMap: {}, // 用于快速查找节点  
				options: {
					series: [{
						type: 'graph',
						layout: 'force',
						roam: true,
						label: {
							show: true,
						},
						edgeSymbol: ['circle', 'arrow'],
						edgeSymbolSize: [4, 10],
						edgeLabel: {
							fontSize: 20,
						},
						data: [],
						links: [],
						lineStyle: {
							width: 2,
							curveness: 0.3,
						},
					}, ],
				},
			};
		},
		mounted() {
			this.chart = echarts.init(this.$refs.chart);
			this.initChart();
		},
		methods: {
			initChart() {
				// 初始化图表数据和结构  
				this.nodeMap = {};
				const graphData = this.flattenNodes(this.nodes[0]); // 从根节点开始展平节点  
				const links = [];

				graphData.forEach(node => {
					this.nodeMap[node.name] = node;
					this.options.series[0].data.push({
						name: node.name,
						value: node.level, // 可以使用level作为value，或者自定义其他属性  
						symbolSize: 50, // 节点大小  
						itemStyle: {
							color: '#a6c84c', // 节点颜色  
						},
					});

					if (node.children && node.children.length > 0) {
						node.children.forEach(childName => {
							const child = this.nodeMap[childName];
							if (child) {
								links.push({
									source: node.name,
									target: child.name,
								});
							}
						});
					}
				});

				this.options.series[0].links = links;
				this.chart.setOption(this.options);
			},
			flattenNodes(node) {
				// 递归展平节点，并只包含expanded为true的子节点  
				const result = [node];
				if (node.expanded && node.children && node.children.length > 0) {
					node.children.forEach(childName => {
						const childNode = this.findNodeByName(childName);
						if (childNode) {
							result.push(...this.flattenNodes(childNode));
						}
					});
				}
				return result;
			},
			findNodeByName(name) {
				// 在nodes数组中查找节点，或者通过nodeMap快速查找  
				return this.nodeMap[name] || this.nodes.find(n => n.name === name);
			},
			toggleNode(name) {
				// 切换节点的展开/收起状态  
				const node = this.findNodeByName(name);
				if (node) {
					node.expanded = !node.expanded;
					this.updateChart();
				}
			},
			updateChart() {
				// 更新图表数据和结构  
				this.chart.clear(); // 清除当前图表  
				this.initChart(); // 重新初始化图表  
			},
		},
		events: {
			'click'(params) {
				// 监听图表点击事件  
				if (params.componentType === 'series' && params.seriesType === 'graph') {
					this.toggleNode(params.name);
				}
			},
		},
	};
</script>

<style scoped>
	/* 添加一些样式以便更好地展示图表 */
</style>
